package com.tintuc24h.untils;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


import com.tintuc24h.models.RssItem;

public class RssHandles extends DefaultHandler {

	public static final String ITEM = "item";
	public static final String TITLE = "title";
	public static final String DESCRIPTION = "description";
	public static final String LINK = "link";
	public static final String DATE = "pubdate";

	private RssItem rssitem;
	private List<RssItem> itemlist = new ArrayList<RssItem>();
	private boolean check = false;
	private StringBuilder sbuilder = new StringBuilder();

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub
		super.characters(ch, start, length);

		if (check && sbuilder != null) {
			sbuilder.append(ch, start, length);
		}

	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		// TODO Auto-generated method stub
		super.endElement(uri, localName, qName);

		if (localName.equalsIgnoreCase(ITEM)) {
			itemlist.add(rssitem);
		} else if (check) {
			if (localName.equalsIgnoreCase(TITLE)) {
				rssitem.setTitle(sbuilder.toString().trim());
			} else if (localName.equalsIgnoreCase(DESCRIPTION)) {
				rssitem.setDescription(sbuilder.toString().trim());
			}
			else if (localName.equalsIgnoreCase(LINK)) {
				rssitem.setLink(sbuilder.toString().trim());
			}
			else if (localName.equalsIgnoreCase(DATE)) {
				rssitem.setDate(sbuilder.toString().trim());
			}
			sbuilder=new StringBuilder();
		}
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		super.startElement(uri, localName, qName, attributes);
		if (localName.equalsIgnoreCase(ITEM)) {
			rssitem = new RssItem();
			check=true;
	}

	}

	public List<RssItem> getItemlist() {
		return itemlist;
	}
}